package com.yb.project.db.controller;

import java.io.IOException;
import java.util.Date;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.yb.common.domain.PageResult;
import com.yb.common.utils.DateUtil;
import com.yb.framework.log.annotation.Log;
import com.yb.framework.log.enums.OperateTypeEnum;
import com.yb.project.base.controller.BaseController;
import com.yb.project.db.domain.Table;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller 
@RequestMapping("/system/db")
@Api(tags = "数据库管理")
public class DatabaseController extends BaseController {
	
	Logger logger = LoggerFactory.getLogger(DatabaseController.class.getName());

	private static String DB_DB = "db/db";
	private static String DB_DATA = "db/data";
	private static String DB_DATA_RECORDS = "/db/data_records";
	
	@GetMapping("")
	@PreAuthorize("hasAuthority('system:db')")
	public String main() {
		return DB_DB;
	}
	
	@GetMapping("/data")
	@PreAuthorize("hasAuthority('system:db:data')")
	public String data() {
		return DB_DATA;
	}
	
	@GetMapping("/data/records")
	@PreAuthorize("hasAuthority('system:db:data:records:info')")
	public String dataRecords(Table table, ModelMap model) {
		model.put("dbName", table.getDbName());
		model.put("tableName", table.getTableName());
		model.put("dataColumnList", JSON.toJSONString(tableService.getDataColumns(table)));
		return DB_DATA_RECORDS;
	}
	
	/**
	 * 数据库列表（表字段管理）
	 */
	@PostMapping("/list")
	@PreAuthorize("hasAuthority('system:db:list')")
	@ApiOperation(value="分页查询数据库", notes="分页查询数据库信息")
	public @ResponseBody PageResult list() {
		return getPageInfo(tableService.getDbList());
	}
	
	/**
	 * 数据库列表（表记录管理）
	 */
	@PostMapping("/data/list")
	@PreAuthorize("hasAuthority('system:db:data:list')")
	@ApiOperation(value="分页查询数据库", notes="分页查询数据库信息")
	public @ResponseBody PageResult dataList() {
		return getPageInfo(tableService.getDbList());
	}
	
	/**
	 * 数据表列表（表记录管理）
	 */
	@PostMapping("/data/table/list")
	@PreAuthorize("hasAuthority('system:db:data:table:list')")
	@ApiOperation(value="分页查询数据表", notes="分页查询数据表信息")
	public @ResponseBody PageResult dataTableList(Table table) {
		return getPageInfo(tableService.getTableList(table));
	}
	
	/**
	 * 数据记录列表（表记录管理）
	 */
	@PostMapping("/data/records/list")
	@PreAuthorize("hasAuthority('system:db:data:records:info')")
	@ApiOperation(value="分页查询数据记录", notes="分页查询数据记录信息")
	public @ResponseBody PageResult dataRecordsList(Table table) {
		return getPageInfo(tableService.getDataRecords(table));
	}
	
	/**
	 * 生成代码
	 */
	@GetMapping("/generatorCode")
	@PreAuthorize("hasAuthority('system:db:code')")
	@ApiOperation(value = "生成代码", notes = "生成代码")
	@Log(label = "生成代码", operateType = OperateTypeEnum.GENCODE)
	public void generatorCode(@RequestParam("dbNames") String dbNames, 
			@RequestParam("tableNames") String tableNames) throws IOException {
		// 获取表名，进行xss过滤
		// HttpServletRequest orgRequest = XssHttpServletRequestWrapper.getOrgRequest(request);
		// String[] dbNameArray = JSON.parseArray(orgRequest.getParameter("dbNames")).toArray(new String[]{});
		// String[] tableNameArray = JSON.parseArray(orgRequest.getParameter("tableNames")).toArray(new String[]{});
		String[] dbNameArray = JSON.parseArray(dbNames).toArray(new String[] {});
		String[] tableNameArray = JSON.parseArray(tableNames).toArray(new String[] {});
		
		// 生成代码
		byte[] data = tableService.generatorCode(dbNameArray[0], tableNameArray);

		response.reset();
		// 如果同名header已存在，则覆盖一个同名header。
		response.setHeader("Content-Disposition", "attachment; filename=\"Code " + 
				DateUtil.date2String(new Date(), "yyyy-MM-dd HH-mm-ss") + ".zip\"");
		// 如果同名header已存在，则追加至原同名header后面。
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");
		// 写入文件
		IOUtils.write(data, response.getOutputStream());
	}
}
